/*
 * @Author: Lin Hongwei
 * @Date: 2022-09-12 10:47:04
 * @LastEditTime: 2022-11-05 14:08:05
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 封装统一请求
 */
import qs from "qs";
import { loginOut } from "./login";
import { useAuthContextHook } from "../contexts/auth-context";
import { useCallback } from "react";
interface OptionType extends RequestInit {
  data?: object;
  token?: string;
}

// const apiUrl = process.env.REACT_APP_BASEURL;
const apiUrl = "/api";
export const http = (
  url: string,
  { data, token, ...options }: OptionType = {}
) => {
  const config = {
    method: "GET",
    headers: {
      token: token || "",
      "Content-Type": data ? "application/json" : "",
    },
    ...options,
  };
  if (config.method.toUpperCase() === "GET") {
    url += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }
  return fetch(`${apiUrl}${url}`, config)
    .then(async (res) => {
      if (res.status == 401) {
        await loginOut();
        window.location.reload();
        return Promise.reject(res);
      }
      if (res.status != 200) return Promise.reject("网络错误!");
      const data = await res.json();
      if (data.code == 200) return data.data;
      return Promise.reject(data || "网络错误!");
    })
    .catch((error) => {
      return Promise.reject({
        message: error.message || "网络错误",
        error,
      });
    });
};

/**
 * @description: 共外界调用的hook
 * @return {*}
 */
export const useHttp = () => {
  const { user } = useAuthContextHook();
  return useCallback(
    (...[url, config]: Parameters<typeof http>) =>
      http(url, {
        ...config,
        token: user?.token || "",
      }),
    [user?.token]
  );
};
